package com.member.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.member.common.enums.CollectionTypeEnum;
import com.member.common.enums.EnableStatusEnum;
import com.member.common.exception.ServiceException;
import com.member.common.utils.DateUtils;
import com.member.common.utils.PageUtils;
import com.member.shop.domain.SysBizProfile;
import com.member.shop.domain.SysBizProfileSource;
import com.member.shop.domain.SysBizUserCollect;
import com.member.shop.mapper.SysBizProfileMapper;
import com.member.shop.service.ISysBizProfileService;
import com.member.shop.service.ISysBizProfileSourceService;
import com.member.shop.service.ISysBizUserCollectService;
import com.member.shop.vo.ImageVo;
import com.member.shop.vo.ProfileVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 资料库Service业务层处理
 *
 * @author lixinchen
 * @date 2024-05-08
 */
@Service
public class SysBizProfileServiceImpl extends ServiceImpl<SysBizProfileMapper, SysBizProfile> implements ISysBizProfileService {
    @Resource
    private SysBizProfileMapper sysBizProfileMapper;

    @Resource
    private ISysBizProfileSourceService sysBizProfileSourceService;

    @Resource
    private ISysBizUserCollectService sysBizUserCollectService;

    /**
     * 查询资料库
     *
     * @param id 资料库主键
     * @return 资料库
     */
    @Override
    public SysBizProfile selectSysBizProfileById(Long id) {
        SysBizProfile sysBizProfile = sysBizProfileMapper.selectById(id);
        LambdaQueryWrapper<SysBizProfileSource> sysBizProfileSourceLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysBizProfileSourceLambdaQueryWrapper.eq(SysBizProfileSource::getProfileId, id);
        List<SysBizProfileSource> sysBizProfileSources = sysBizProfileSourceService.selectSysBizProfileSourceList(sysBizProfileSourceLambdaQueryWrapper);
        sysBizProfile.setProfileSourceList(sysBizProfileSources);
        return sysBizProfile;
    }

    /**
     * 查询资料库列表
     *
     * @param queryWrapper 资料库
     * @return 资料库
     */
    @Override
    public List<SysBizProfile> selectSysBizProfileList(LambdaQueryWrapper<SysBizProfile> queryWrapper) {
        return sysBizProfileMapper.selectList(queryWrapper);
    }

    /**
     * 新增资料库
     *
     * @param sysBizProfile 资料库
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertSysBizProfile(SysBizProfile sysBizProfile) {
        sysBizProfile.setCreateTime(DateUtils.getNowDate());
        int insert = sysBizProfileMapper.insert(sysBizProfile);
        List<SysBizProfileSource> profileSourceList = sysBizProfile.getProfileSourceList();
        if (!CollectionUtils.isEmpty(profileSourceList)) {
            for (SysBizProfileSource sysBizProfileSource : profileSourceList) {
                sysBizProfileSource.setProfileId(sysBizProfile.getId());
            }
            sysBizProfileSourceService.saveBatch(profileSourceList);
        }
        return insert;
    }

    /**
     * 修改资料库
     *
     * @param sysBizProfile 资料库
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateSysBizProfile(SysBizProfile sysBizProfile) {
        sysBizProfile.setUpdateTime(DateUtils.getNowDate());
        int i = sysBizProfileMapper.updateById(sysBizProfile);
        List<SysBizProfileSource> profileSourceList = sysBizProfile.getProfileSourceList();
        sysBizProfileSourceService.deleteByProfileId(sysBizProfile.getId());
        if (!CollectionUtils.isEmpty(profileSourceList)) {
            for (SysBizProfileSource sysBizProfileSource : profileSourceList) {
                sysBizProfileSource.setProfileId(sysBizProfile.getId());
                sysBizProfileSource.setUpdateTime(DateUtils.getNowDate());
            }
            sysBizProfileSourceService.saveBatch(profileSourceList);
        }
        return i;
    }

    /**
     * 批量删除资料库
     *
     * @param ids 需要删除的资料库主键
     * @return 结果
     */
    @Override
    public int deleteSysBizProfileByIds(Long[] ids) {
        return sysBizProfileMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除资料库信息
     *
     * @param id 资料库主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteSysBizProfileById(Long id) {
        sysBizProfileSourceService.deleteByProfileId(id);
        return sysBizProfileMapper.deleteById(id);
    }

    @Override
    public List<SysBizProfile> selectSysBizProfileList(SysBizProfile sysBizProfile) {
        return sysBizProfileMapper.selectSysBizProfileList(sysBizProfile);
    }

    @Override
    public List<ProfileVo> queryProfileSource(Long categoryId, Integer type, Long userId, Integer pageNum, Integer pageSize) {
        if (categoryId == null || type == null || userId == null) {
            throw new ServiceException("参数为空");
        }
        List<ProfileVo> profileVoList = new ArrayList<>();
        LambdaQueryWrapper<SysBizProfile> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysBizProfile::getType, type);
        queryWrapper.eq(SysBizProfile::getCategoryId, categoryId);
        queryWrapper.eq(SysBizProfile::getStatus, EnableStatusEnum.ENABLE.getKey());
        queryWrapper.orderByDesc(SysBizProfile::getSort);
        queryWrapper.orderByDesc(SysBizProfile::getId);
        try {
            if (type == 20 || type == 30) {
                PageUtils.clearPage();
            }
            List<SysBizProfile> sysBizProfiles = sysBizProfileMapper.selectList(queryWrapper);
            if (CollectionUtils.isEmpty(sysBizProfiles)) {
                return Collections.emptyList();
            }
            profileVoList.addAll(processProfileSources(sysBizProfiles, userId, type, pageNum, pageSize));
        } catch (Exception e) {
            // 异常处理逻辑（这里简单地打印异常堆栈，根据实际情况，您可能需要更复杂的处理逻辑）
            log.error("查询资料库列表发生异常", e);
        }
        return profileVoList;
    }

    private List<ProfileVo> processProfileSources(List<SysBizProfile> sysBizProfiles, Long userId, Integer type, Integer pageNum, Integer pageSize) {
        List<ProfileVo> profileVoList = new ArrayList<>();
        switch (type) {
            case 10: // 图片
                profileVoList.addAll(sysBizProfiles.stream().map(sysBizProfile -> {
                    List<SysBizProfileSource> profileSourceList = sysBizProfileSourceService.selectSysBizProfileSourceList(new LambdaQueryWrapper<SysBizProfileSource>()
                            .eq(SysBizProfileSource::getProfileId, sysBizProfile.getId())
                            .orderByDesc(SysBizProfileSource::getSort)
                            .orderByDesc(SysBizProfileSource::getId));
                    List<ImageVo> imageVoList = new ArrayList<>();
                    if (!CollectionUtils.isEmpty(profileSourceList)) {
                        // 通过Java 8 Stream API 改善循环和条件判断
                        imageVoList = profileSourceList.stream().map(sysBizProfileSource -> {
                            ImageVo imageVo = new ImageVo();
                            imageVo.setId(sysBizProfileSource.getId());
                            imageVo.setImageUrl(sysBizProfileSource.getUrl());
                            imageVo.setImageName(sysBizProfileSource.getName());
                            imageVo.setCreateTime(sysBizProfileSource.getCreateTime());
                            imageVo.setIsCollection(isCollected(sysBizProfileSource.getId(), userId, CollectionTypeEnum.IMAGE.getKey()));
                            return imageVo;
                        }).collect(Collectors.toList());
                    }
                    ProfileVo profileVo = new ProfileVo();
                    profileVo.setId(sysBizProfile.getId());

                    profileVo.setType(sysBizProfile.getType());
                    profileVo.setCover(sysBizProfile.getCover());
                    profileVo.setCoverTitle(sysBizProfile.getCoverTitle());
                    profileVo.setImageUrlList(imageVoList);
                    return profileVo;
                }).collect(Collectors.toList()));
                break;
            case 20: // 视频
                List<Long> collect = sysBizProfiles.stream().map(SysBizProfile::getId).collect(Collectors.toList());
                PageUtils.startPage(pageNum, pageSize);
                List<SysBizProfileSource> profileSourceList = sysBizProfileSourceService.selectSysBizProfileSourceList(new LambdaQueryWrapper<SysBizProfileSource>()
                        .in(SysBizProfileSource::getProfileId, collect)
                        .orderByDesc(SysBizProfileSource::getSort)
                        .orderByDesc(SysBizProfileSource::getId));
                if (!CollectionUtils.isEmpty(profileSourceList)) {
                    // 通过Java 8 Stream API 改善循环和条件判断
                    profileVoList.addAll(profileSourceList.stream().map(sysBizProfileSource -> {
                        ProfileVo profileVo = new ProfileVo();
                        profileVo.setId(sysBizProfileSource.getId());
                        profileVo.setType(20);

                        profileVo.setVideoName(sysBizProfileSource.getName());
                        profileVo.setVideoUrl(sysBizProfileSource.getUrl());
                        profileVo.setCreateTime(sysBizProfileSource.getCreateTime());
                        profileVo.setIsCollection(isCollected(sysBizProfileSource.getId(), userId, CollectionTypeEnum.VIDEO.getKey()));
                        return profileVo;
                    }).collect(Collectors.toList()));
                }
                break;
            case 30:
                List<Long> collect2 = sysBizProfiles.stream().map(SysBizProfile::getId).collect(Collectors.toList());
                PageUtils.startPage(pageNum, pageSize);
                List<SysBizProfileSource> profileSourceList2 = sysBizProfileSourceService.selectSysBizProfileSourceList(new LambdaQueryWrapper<SysBizProfileSource>()
                        .in(SysBizProfileSource::getProfileId, collect2)
                        .orderByDesc(SysBizProfileSource::getSort)
                        .orderByDesc(SysBizProfileSource::getId));
                if (!CollectionUtils.isEmpty(profileSourceList2)) {
                    // 通过Java 8 Stream API 改善循环和条件判断
                    profileVoList.addAll(profileSourceList2.stream().map(sysBizProfileSource -> {
                        ProfileVo profileVo = new ProfileVo();
                        profileVo.setId(sysBizProfileSource.getId());
                        profileVo.setType(30);
                        profileVo.setFileName(sysBizProfileSource.getName());
                        profileVo.setFileUrl(sysBizProfileSource.getUrl());
                        profileVo.setCreateTime(sysBizProfileSource.getCreateTime());
                        profileVo.setIsCollection(isCollected(sysBizProfileSource.getId(), userId, CollectionTypeEnum.FILE.getKey()));
                        return profileVo;
                    }).collect(Collectors.toList()));
                }
                break;
            default:
                break;
        }
        return profileVoList;
    }

    @Override
    public boolean isCollected(Long sourceId, Long userId, Integer type) {
        return !sysBizUserCollectService.list(new LambdaQueryWrapper<SysBizUserCollect>()
                .eq(SysBizUserCollect::getUserId, userId)
                .eq(SysBizUserCollect::getType, type)
                .eq(SysBizUserCollect::getGoodsId, sourceId)).isEmpty();
    }

    @Override
    public int updateSysBizProfile2(SysBizProfile sysBizProfile) {
        sysBizProfile.setUpdateTime(DateUtils.getNowDate());
        return sysBizProfileMapper.updateById(sysBizProfile);
    }
}
